<script lang="ts">
    import { createUniqueId } from "../utils/createUniqueId";
    import usezIndex from "../utils/usezIndex";
    import type { NoticeConfig, NoticeStoreData } from "./Notice";
    import NoticeBox from "./NoticeBox.svelte";

    const props = $props();
    let zindex = $state(0);

    const store = $state<NoticeStoreData>({
        topLeft: [],
        topRight: [],
        bottomLeft: [],
        bottomRight: [],
    });

    const noticeMap = $state<any>({});

    const onClose = (key: string, dock: "topRight" | "topLeft" | "bottomLeft" | "bottomRight") => {
        const arr: NoticeConfig[] = store[dock].filter((item: NoticeConfig) => {
            return item.key !== key;
        });

        const item: NoticeConfig | undefined = store[dock].find((aitem: any) => {
            return aitem.key === key;
        });
        store[dock] = arr;

        delete noticeMap[key];
        if (item) {
            item.onclose?.();
        }
    };

    export const close = (key: string) => {
        noticeMap[key]?.hide();
    };

    export const open = (config: NoticeConfig) => {
        if (!config.dock) {
            config.dock = "topRight";
        }
        if (config.key === undefined) {
            config.key = createUniqueId();
        }
        if (config.duration === undefined) {
            config.duration = 4.5;
        }

        store[config.dock].push(config);

        zindex = usezIndex();
    };

    export const info = (config: NoticeConfig) => {
        config.type = "info";
        open(config);
    };
    export const success = (config: NoticeConfig) => {
        config.type = "success";
        open(config);
    };
    export const warning = (config: NoticeConfig) => {
        config.type = "warning";
        open(config);
    };
    export const error = (config: NoticeConfig) => {
        config.type = "error";
        open(config);
    };
    export const help = (config: NoticeConfig) => {
        config.type = "help";
        open(config);
    };
</script>

<div class="cm-notification" style:zindex>
    {#if store.topLeft?.length}
        <NoticeBox {noticeMap} data={store.topLeft} docker="top-left" onclose={onClose} />
    {/if}
    {#if store.topRight?.length}
        <NoticeBox {noticeMap} data={store.topRight} docker="top-right" onclose={onClose} />
    {/if}
    {#if store.bottomLeft?.length}
        <NoticeBox {noticeMap} data={store.bottomLeft} docker="bottom-left" onclose={onClose} />
    {/if}
    {#if store.bottomRight?.length}
        <NoticeBox {noticeMap} data={store.bottomRight} docker="bottom-right" onclose={onClose} />
    {/if}
</div>
